<template>
  <div id="UserListPage">
    <div v-if="loading" class="custom-spin">
      <a-spin size="large" />
    </div>
    <a-card class="container">
      <a-form
        :model="formSearchParams"
        :style="{ marginBottom: '20px' }"
        layout="inline"
        @submit="doSearch"
      >
        <a-form-item name="orderDates" label="起止时间">
          <a-range-picker
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            :placeholder="['开始时间', '结束时间']"
            v-model:value="formSearchParams.orderDates"
            :default-value="[defaultStartTime, defaultEndTime]"
          />
        </a-form-item>
        <a-form-item name="specifications" label="规格">
          <a-switch v-model:checked="formSearchParams.specifications" @change="doChange6" />
        </a-form-item>
        <a-form-item name="userName" label="合同编号">
          <a-switch v-model:checked="formSearchParams.contractNumberGroup" @change="doChange1" />
        </a-form-item>
        <a-form-item name="userName" label="收货单位">
          <a-switch v-model:checked="formSearchParams.consigneeGroup" @change="doChange" />
        </a-form-item>
        <a-form-item name="userName" label="运输单位">
          <a-switch v-model:checked="formSearchParams.transportUnitGroup" @change="doChange3" />
        </a-form-item>
        <a-form-item name="userName" label="发货单位">
          <a-switch v-model:checked="formSearchParams.dispatcherGroup" @change="doChange5" />
        </a-form-item>
<!--        <a-form-item name="userName" label="发货人">-->
<!--          <a-switch v-model:checked="formSearchParams.dispatcherPeopleGroup" @change="doChange4" />-->
<!--        </a-form-item>-->
<!--        specifications-->


        <a-form-item style="margin-top: 20px">
          <a-button type="primary" html-type="submit" style="width: 100px"> 搜索</a-button>
          <a-button
            @click="doReset"
            type="default"
            html-type="button"
            style="margin-left: 15px; width: 100px"
          >
            重置
          </a-button>
          <a-button
            @click="doexport"
            type="default"
            html-type="button"
            style="margin-left: 15px; width: 100px"
          >
            导出
          </a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="columns" :data-source="dataList">
        <template #headerCell="{ column }">
          <template v-if="column.key === 'username'">
            <span>
              <smile-outlined />
              {{ column.title }}
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="showModal('edit', record)" style="padding: 0"
              >查看详情
            </a-button>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell v-for="(item,index) in columns" :key="item.key">
                {{ getSummary(item.dataIndex as string,item,index) }}
              </a-table-summary-cell>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </a-card>
    <HomeModal
      :model-value="open"
      :title="title"
      :on-cancel="onCancel"
      :on-ok="handleOk"
      :record="currentRow"
    />
  </div>
</template>
<script lang="ts" setup>
import { SmileOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { ref, watchEffect } from 'vue'
import HomeModal from './HomeModal.vue'
import type { SaleOrderQueryReqDTO, SaleOrderTotalRespDTO, UserVo } from '@/api/globals'
import Api from '@/api'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 导入所需的语言包
dayjs.locale('zh-cn'); // 使用中文语言包

const open = ref<boolean>(false)
const title = ref<string>('详情')
const currentRow = ref<object>({})

// 设置默认时间
const defaultStartTime = dayjs().subtract(1, 'day').startOf('day'); // 前一天的 00:00:00
const defaultEndTime = dayjs().startOf('day'); // 当天的 00:00:00
const searchParams = ref({
  orderDates:[defaultStartTime,defaultEndTime],
  specifications:true
})


// 确认提交 可能是更新可能是创建
const handleOk = () => {
  open.value = false
  currentRow.value = {}
  fetchData()
}

const showModal = (type: string, record: UserVo) => {
  open.value = true
  currentRow.value = {
    ...searchParams.value,
    ...record,
  }
}

const onCancel = () => {
  open.value = false
  currentRow.value = {}
}


const formSearchParams = ref<SaleOrderQueryReqDTO>({
  specifications:true
} as SaleOrderQueryReqDTO)

/**
 * 执行搜索
 */
const doSearch = () => {
  console.log(formSearchParams.value)
  // @ts-ignore
  searchParams.value = {
    ...formSearchParams.value,
  }
}

// 数据
const dataList = ref<SaleOrderTotalRespDTO[]>([])

// 获取数据
const fetchData = async () => {
  const res = await Api.general.totalListPage({
    data: {
      ...searchParams.value,
    } as any,
  })
  if (res.data) {
    dataList.value = res.data || []
  } else {
    message.error('获取数据失败 ' + res.msg)
  }
}

watchEffect(() => {
  fetchData()
})

/**
 * 重置搜索条件
 */
const doReset = () => {
  searchParams.value = {
    orderDates:[defaultStartTime,defaultEndTime],
    specifications:true
  }
  formSearchParams.value = {
    // @ts-ignore
    orderDates:[defaultStartTime,defaultEndTime],
    specifications:true
  }
}

const columns = ref([
  {
    key: 'goodsName',
    title: '货品名称',
    dataIndex: 'goodsName',
  },
  {
    key: 'specifications',
    title: '规格',
    dataIndex: 'specifications',
  },
  {
    key: 'totalWeight',
    title: '总重量',
    dataIndex: 'totalWeight',
    summary: true,
  },
  {
    key: 'vehicleNum',
    title: '车数',
    dataIndex: 'vehicleNum',
    summary: true,
  },

  {
    key: 'voteNum',
    title: '票数',
    dataIndex: 'voteNum',
    summary: true,
  },
  {
    key: 'checkNum',
    title: '已核对票数',
    dataIndex: 'checkNum',
    summary: true,
  },
  {
    key: 'money',
    title: '应收金额',
    dataIndex: 'money',
    summary: true,

  },
  {
    key: 'amountReceivable',
    title: '实收金额',
    dataIndex: 'amountReceivable',
    summary: true,

  },
  {
    title: '操作',
    key: 'action',
  },
])
const doChange1 = (checked: boolean | string | number) => {
  if (checked) {
    columns.value = [
      {
        key: 'contractNumber',
        title: '合同编号',
        dataIndex: 'contractNumber',
      },
      ...columns.value,
    ]
  } else {
    columns.value = columns.value.filter((item) => item.key !== 'contractNumber')
  }
  doSearch()
}

const doChange = (checked: boolean | string | number) => {
  if (checked) {
    columns.value = [
      {
        key: 'consignee',
        title: '收货单位',
        dataIndex: 'consignee',
      },
      ...columns.value,
    ]
  } else {
    columns.value = columns.value.filter((item) => item.key !== 'consignee')
  }
  doSearch()
}

const doChange3 = (checked: boolean | string | number) => {
  if (checked) {
    columns.value = [
      {
        key: 'transportUnit',
        title: '运输单位',
        dataIndex: 'transportUnit',
      },
      ...columns.value,
    ]
  } else {
    columns.value = columns.value.filter((item) => item.key !== 'transportUnit')
  }
  doSearch()
}
// const doChange4 = (checked: boolean | string | number) => {
//   if (checked) {
//     columns.value = [
//       {
//         key: 'deliveryMan',
//         title: '送货人',
//         dataIndex: 'deliveryMan',
//       },
//       ...columns.value,
//     ]
//   } else {
//     columns.value = columns.value.filter((item) => item.key !== 'deliveryMan')
//   }
//   doSearch()
// }
const doChange6 = (checked: boolean | string | number) => {
  if (checked) {
    columns.value = [
      {
        key: 'specifications',
        title: '规格',
        dataIndex: 'specifications',
      },
      ...columns.value,
    ]
  } else {
    columns.value = columns.value.filter((item) => item.key !== 'specifications')
  }
  doSearch()
}
const doChange5 = (checked: boolean | string | number) => {
  if (checked) {
    columns.value = [
      {
        key: 'dispatcher',
        title: '发货单位',
        dataIndex: 'dispatcher',
      },
      ...columns.value,
    ]
  } else {
    columns.value = columns.value.filter((item) => item.key !== 'dispatcher')
  }
  doSearch()
}

const getSummary = (field: string,c:any,index:number) => {
  if(index==0){
    return "合计";
  }
  if(c.summary){
    return dataList.value.reduce((sum, record) => {
      // @ts-ignore
      const value = record[field]  || 0;
      return typeof value === 'number' ? sum + value : sum;
    }, 0).toFixed(2);
  }else {
    return "";
  }

};
const loading = ref(false);
const doexport = async () =>{
  loading.value = true; // 显示加载提示
  try {
    const response = await Api.general.exportData({
      data: {
        ...searchParams.value
      } as any,
      responseType: 'blob', // 确保后端返回的是blob类型
    });

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response as Blob]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '卖货查询.xlsx'); // 设置下载的文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error:any) {
    message.error('导出失败');
  } finally {
    loading.value = false; // 隐藏加载提示
  }
}
</script>
<style scoped>
.custom-spin {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
</style>
